<?php


namespace app\middleware;


use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class Authentication implements MiddlewareInterface
{

    /**
     * 名单认证
     * @param Request $request
     * @param callable $handler
     * @return Response
     */
    public function process(Request $request, callable $handler): Response
    {
        $getLocalIpArray = ['127.0.0.1','192.168.138.128'];
        $getLocalPortArray = ['8787','8080'];
        $urlArray=['127.0.0.1:8787'];
        //当前的域名访问
        $url  = $request->host();
        //获取服务端IP
        $getLocalIp = $request->getLocalIp();
        if(!in_array($getLocalIp,$getLocalIpArray) || !in_array($url,$urlArray)){
            $return = [
                'code' => 1,
                'msg'  => '非法服务器访问',
                'data' => []
            ];
            $return['debug'] = uniqid();
            return json($return);
        }
        //获取服务端端口
        $getLocalPort = $request->getLocalPort();
        if(!in_array($getLocalPort,$getLocalPortArray)){
            $return = [
                'code' => 1,
                'msg'  => '非法服务器访问',
                'data' => []
            ];
            $return['debug'] = uniqid();
            return json($return);
        }
        return $handler($request);
    }
}
